#include "forward_buffer.h"
#include "common.h"

forward_buffer::forward_buffer() : buffer_ptr(NULL), buffer_len(0), start_pos(0), end_pos(0){

}

forward_buffer::~forward_buffer(){
	release();
}

void forward_buffer::alloc(unsigned int alloc_size){
	if (alloc_size == 0){
		return;
	}

	if (is_valid()){
		release();
	}

	if (buffer_ptr == NULL){
		buffer_ptr = new char[alloc_size];
		buffer_len = alloc_size;
	}
}

bool forward_buffer::is_valid(){
	return (buffer_ptr != NULL && buffer_len > 0);
}

void forward_buffer::zero(){
	if (is_valid()){
		bzero(buffer_ptr, buffer_len);
	}
	start_pos = 0;
	end_pos = 0;
}

void forward_buffer::release(){
	if (buffer_ptr != NULL){
		delete [] buffer_ptr;
		buffer_ptr = NULL;
	}
	buffer_len = 0;
	start_pos = 0;
	end_pos = 0;
}

unsigned int forward_buffer::get_buffer_len(){
	return buffer_len;
}

char* forward_buffer::get_data_ptr(){
	return buffer_ptr+start_pos;
}

unsigned int forward_buffer::get_data_len(){
	return end_pos-start_pos;
}

void forward_buffer::write(char* ptr, unsigned int len){
	if (end_pos + len > buffer_len){
		return;
	}
	memcpy(buffer_ptr+end_pos, ptr, len);
	end_pos += len;
}

void forward_buffer::erase_front(unsigned int len){
	unsigned int data_len = get_data_len();
	if (len > data_len){

	}else if (len == data_len){
		zero();
	}else{
		start_pos += len;
	}
}
